from typing import List
from ninja import Router
from django.shortcuts import get_object_or_404
from django.http import Http404
from ..models import Route
from .schemas import RouteCreate, RouteUpdate, RouteResponse, RoutePublicResponse
from apps.user_management.api.auth import DispatcherAuth

# 创建路由器
router = Router(tags=["线路管理"])

# 公共接口（无需认证）
@router.get("/", response=List[RoutePublicResponse], summary="获取线路列表")
def list_routes(request):
    """获取所有运营中的线路列表"""
    return Route.objects.filter(status='active')

@router.get("/{route_id}", response=RoutePublicResponse, summary="获取线路详情")
def get_route(request, route_id: str):
    """获取指定线路的详细信息"""
    route = get_object_or_404(Route, route_id=route_id, status='active')
    return route

# 调度员接口（需要认证）
@router.post("/", auth=DispatcherAuth(), response={201: RouteResponse}, summary="创建新线路")
def create_route(request, payload: RouteCreate):
    """创建新的线路"""
    route = Route.objects.create(**payload.model_dump())
    return 201, route

@router.put("/{route_id}", auth=DispatcherAuth(), response=RouteResponse, summary="更新线路信息")
def update_route(request, route_id: str, payload: RouteUpdate):
    """更新指定线路的信息"""
    route = get_object_or_404(Route, route_id=route_id)
    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(route, field, value)
    route.save()
    return route

@router.delete("/{route_id}", auth=DispatcherAuth(), response={204: None}, summary="删除线路")
def delete_route(request, route_id: str):
    """删除指定线路（逻辑删除）"""
    route = get_object_or_404(Route, route_id=route_id)
    route.status = 'closed'
    route.save()
    return 204, None 